import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  Dimensions,
  StyleSheet,
  TouchableNativeFeedback,
  Alert,
  DeviceEventEmitter,
} from 'react-native';

import Theme from '../../native-base-theme/variables/commonColor';
import LineItem from '../../components/detail/lineItem';
import Option from '../main/incident/flowPage/acceptOptions';
import * as request from '../../services/pollingRequest';
import { UtilToast } from '../../utils/util-method';
import ZlstIcon from '../../components/zlst-icons';

const deviceWidth = Dimensions.get('window').width;
class CreatTask extends Component {
  static navigationOptions = {
    title: '创建点巡检任务',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  optionList = ['日常巡检', '专业巡检']

  constructor(props) {
    super(props);
    this.state = {
      userName: '',
      userCode: '',
      orgName: '',
      showDate: '',
      ckIndex: 0,
      update: '',
    };
  }

  componentWillMount() {
    console.log("_getTaskInfo == ", this.props.navigation);

    const userName = global.user.staff.name; // 展示人名
    const userCode = global.user.name; // 提交数据的人员code
    const orgName = global.user.organization.name; // 展示的人员班组
    const date = new Date();
    const update = date.getTime(); // 上传的日期
    const year = date.getFullYear();
    let month = date.getMonth();
    month = (month + 1) > 9 ? (month + 1) : `0${month + 1}`;
    const day = date.getDate();
    const showDate = `${year}-${month}-${day}`; // 展示日期
    this.setState({
      userName,
      userCode,
      orgName,
      showDate,
      update,
    });
  }

  itemClick = (data, ckIndex) => {
    this.setState({
      ckIndex,
    });
  }

  _confirmCreateTask = async () => {
    Alert.alert(
      '提示',
      '是否创建任务',
      [
        {
          text: '否',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '是',
          onPress: () => {
            this.toServer();
          },
        },
      ],
    );
  }

  toServer = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const resp = await request.createTask({
        checkDate: this.state.update,
        checkType: `0${this.state.ckIndex + 1}`,
        checkUserCode: this.state.userCode,
        checkStaffName: this.state.userName,
      });
      DeviceEventEmitter.emit('showLoading', false);
      if (resp && resp.resultCode == '0') { // 成功
        DeviceEventEmitter.emit('refreshTaskPageEvent');
        global.navigation.navigate({
          routeName: 'Task',
          params: {
            checkrecordId: resp.data.checkrecordId,
            routeKey: this.props.navigation.state.key,
          },
        });
      } else {
        UtilToast(resp.resultMsg || '创建任务失败', 'danger');
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      UtilToast('创建任务失败', 'danger');
      console.log('error,', error);
    }
  }

  _cancelCreateTask = () => {
    Alert.alert(
      '提示',
      '是否取消创建任务',
      [
        {
          text: '否',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '是',
          onPress: () => {
            this.props.navigation.goBack();
          },
        },
      ],
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          <LineItem item={{ label: '巡检人', value: this.state.userName }} />
          <LineItem item={{ label: '巡检班组', value: this.state.orgName }} />
          <LineItem item={{ label: '巡检日期', value: this.state.showDate }} />
          <LineItem item={{ label: '巡检类型' }}>
            <Option
              style={{ height: 42 }}
              containerStyle={{ paddingLeft: 0, paddingRight: 0 }}
              optionsList={this.optionList}
              ckIndex={this.state.ckIndex}
              onClick={this.itemClick}
            />
          </LineItem>
        </View>
        <View>
          <Image
            source={require('../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={styles.operationBtns}>
            <TouchableNativeFeedback
              onPress={this._confirmCreateTask}
              key={1}
            >
              <View style={{ flex: 1 }}>
                <Text style={styles.btnText}>确定</Text>
              </View>
            </TouchableNativeFeedback>
            <TouchableNativeFeedback
              onPress={this._cancelCreateTask}
              key={2}
            >
              <View style={{ flex: 1 }}>
                <Text style={styles.btnText}>取消</Text>
              </View>
            </TouchableNativeFeedback>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: Theme.myPrimary,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
  },
  operationBtns: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  btnText: {
    textAlign: 'center',
    color: '#ffffff',
    paddingTop: 15,
    paddingBottom: 15,
  },
  item: {
    padding: 10,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: '#ffffff',
    color: '#ffffff',
    marginRight: 10,
  },
  ckItem: {
    padding: 10,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: '#207aff',
    color: '#ffffff',
    backgroundColor: '#207aff',
    marginRight: 10,
  },
});

export default CreatTask;
